﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using SLMitsuControls;
using Microsoft.SharePoint.Client;
using System.IO;
using System.Xml.Linq;


namespace SLThumbsExtPT
{
    public partial class MainPage : UserControl, IDataProvider
    {
        ClientContext ctx;
        List<Button> lstBtnImage = new List<Button>();
        private string strUrlImage;
        private string strUrlDocXml;
        int pageCount;
        public MainPage()
        {
            InitializeComponent();
            
            //ctx = ClientContext.Current;
            


        }

        int IDataProvider.GetCount()
        {
            return lstBtnImage.Count;
        }

        object IDataProvider.GetItem(int index)
        {
            return lstBtnImage[index];
        }
        private void ReadCallback(IAsyncResult asynchronousResult)
        {
            HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
            using (StreamReader streamReader1 = new StreamReader(response.GetResponseStream()))
            {
                string resultString = streamReader1.ReadToEnd();
                XDocument xdoc = XDocument.Parse(resultString);
                strUrlImage = xdoc.Element("mobileDoc").Element("pageImage").Attribute("url").Value;
                strUrlDocXml = xdoc.Element("mobileDoc").Element("pageXml").Attribute("url").Value;
                pageCount = int.Parse(xdoc.Element("mobileDoc").Element("document").Element("pageset").Attribute("count").Value);
                HttpWebRequest requestDocXML = (HttpWebRequest)HttpWebRequest.Create(ctx.Url + "/_layouts/" + strUrlDocXml + "&n=p_1_10.xml");
                requestDocXML.BeginGetResponse(new AsyncCallback(ReadDocXmlCallback), requestDocXML);
            }
        }
        private void ReadDocXmlCallback(IAsyncResult asynchronousResult)
        {
            HttpWebRequest requestDocXML = (HttpWebRequest)asynchronousResult.AsyncState;
            HttpWebResponse responseDocXml = (HttpWebResponse)requestDocXML.EndGetResponse(asynchronousResult);
            using (StreamReader streamReader1 = new StreamReader(responseDocXml.GetResponseStream()))
            {
                string resultString = streamReader1.ReadToEnd();
                XDocument xdoc = XDocument.Parse(resultString);
                string firstPageID = xdoc.Element("Pages").Element("Page").Element("P").Element("L").Element("LT").Attribute("p").Value;
                this.Dispatcher.BeginInvoke(() =>
                {
                    int PageID = int.Parse(firstPageID);
                    for (int miind = PageID; miind <= pageCount; miind++)
                    {
                        string strUrl1 = ctx.Url + "/_layouts/" + strUrlImage + "&n=p" + miind + ".img&width=210&height=297";
                        Uri uri1 = new Uri(strUrl1);
                        Button btn = new Button();

                        Image imgCtrl = new Image();
                        ImageSourceConverter imgs = new ImageSourceConverter();
                        imgCtrl.SetValue(Image.SourceProperty, imgs.ConvertFromString(uri1.AbsoluteUri));
                        imgCtrl.Stretch = Stretch.UniformToFill;
                        btn.Content = imgCtrl;
                        btn.HorizontalAlignment = HorizontalAlignment.Stretch;
                        btn.VerticalAlignment = VerticalAlignment.Stretch;
                        lstBtnImage.Add(btn);
                    }
                });
            }

            this.Dispatcher.BeginInvoke(delegate()
            {
                int i = 0;
                foreach (var b in lstBtnImage)
                {
                    if (i % 2 == 0)
                        b.Click += Button_Click;
                    else
                        b.Click += Button_Click_1;
                    i++;
                }
                book.SetData(this);
            });
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            book.AnimateToNextPage(500);
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            book.AnimateToPreviousPage(500);
        }
        public static string strDocUrl { get; set; }
        public static string strWebUrl { get; set; }
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            ctx = new ClientContext(strWebUrl);
            HttpWebRequest request;
            if (System.IO.Path.GetExtension(strDocUrl) == ".docx")
            {
                request = (HttpWebRequest)HttpWebRequest.Create(ctx.Url + "/_layouts/MobileDocHandler.ashx?doc=" + strDocUrl);
                request.BeginGetResponse(new AsyncCallback(ReadCallback), request);
            }
            else
            {
                request = (HttpWebRequest)HttpWebRequest.Create(ctx.Url + "/_layouts/SPThumbnailExtender/MobileXPSHandler.ashx?xps=" + strDocUrl + "&count=true");
                request.BeginGetResponse(new AsyncCallback(ReadCallbackXps), request);
            }


        }
        private void ReadCallbackXps(IAsyncResult asynchronousResult)
        {
            HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
            using (StreamReader streamReader1 = new StreamReader(response.GetResponseStream()))
            {
                string resultString = streamReader1.ReadToEnd();
                int PageCount = int.Parse(resultString);
                for (int miind = 0; miind < PageCount; miind++)
                {
                    string strUrl1 = ctx.Url + "/_layouts/SPThumbnailExtender/MobileXPSHandler.ashx?xps=" + strDocUrl + "&n=" + miind + "&width=1260&height=1782";
                    Uri uri1 = new Uri(strUrl1);
                    this.Dispatcher.BeginInvoke(delegate()
           {
               Button btn = new Button();

               Image imgCtrl = new Image();
               ImageSourceConverter imgs = new ImageSourceConverter();
               imgCtrl.SetValue(Image.SourceProperty, imgs.ConvertFromString(uri1.AbsoluteUri));
               imgCtrl.Stretch = Stretch.UniformToFill;
               btn.Content = imgCtrl;
               btn.HorizontalAlignment = HorizontalAlignment.Stretch;
               btn.VerticalAlignment = VerticalAlignment.Stretch;
               lstBtnImage.Add(btn);
           });
                }
            }
            this.Dispatcher.BeginInvoke(delegate()
            {
                int i = 0;
                foreach (var b in lstBtnImage)
                {
                    if (i % 2 == 0)
                        b.Click += Button_Click;
                    else
                        b.Click += Button_Click_1;
                    i++;
                }
                book.SetData(this);
            });
        }
    }
}
